import {Button, Form, message, Modal, Radio, Tag} from 'antd';
import React, {useRef, useState} from 'react';
import {PageContainer} from '@ant-design/pro-layout';
import {isSuccess} from "@/utils/utils";
import {Marketing} from "@/services/api-functions";
import {SYS_ENUMS} from "@/utils/constants";
import ProTable, {ActionType, ProColumns} from "@ant-design/pro-table";
import {ExclamationCircleOutlined, PlusOutlined} from "@ant-design/icons";
import {ModalForm, ProFormSelect} from "@ant-design/pro-form";
import {isArray} from "lodash";


export const pushAdd = async (fields: any) => {
  try {
    const userStrategy = !isArray(fields.userStrategy) ? [fields.userStrategy.value] : fields.userStrategy
    if (isSuccess((await Marketing.taskAdd({
      contentId: fields.contentId,
      pushType: fields.pushType,
      userStrategy: userStrategy??['ALL'],
    }))?.code)) {
      message.success('添加成功');
      return true;
    }
    return false
  } catch (error) {
    return false;
  }
};

export const pushCancel = async (select: any) => {
  if (!select) return false;
  try {
    message.loading('正在取消');
    if (isSuccess((await Marketing.taskCancel(select.id))?.code)) {
      message.success('取消成功');
      return true;
    }
    return false
  } catch (error) {
    return false;
  }
};


const ArticleList: React.FC<any> = ({}) => {
  const initCountInfo = {
    ALL: undefined,
    INIT: undefined,
    CANCEL: undefined,
    FINISH: undefined,
    FAIL: undefined,
    DOING: undefined
  };
  const [auditFormRef] = Form.useForm()
  const [auditState, setAuditState] = useState<'ALL' | 'INIT' | 'CANCEL' | 'DOING' | 'FINISH' | 'FAIL'>('ALL');
  const [countInfo, setCountInfo] = useState<{ ALL: number | undefined, INIT: number | undefined, CANCEL: number | undefined, FINISH: number | undefined, FAIL: number | undefined, DOING: number | undefined }>(initCountInfo);
  const [auditVisible, handleAuditVisible] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const columns: ProColumns[] = [
    {
      title: '标题',
      dataIndex: 'contentTitle',
      ellipsis: true,
      width: 250,
      fixed: 'left',
    },
    {
      title: '发布人',
      dataIndex: ['userDto', 'nickName'],
      ellipsis: true,
      hideInSearch: true,
      width: 120,
    },
    {
      title: '推送类型',
      dataIndex: 'pushType',
      valueEnum: SYS_ENUMS.PUSH_TYPE,
      width: 130,
      hideInForm: true,
      hideInSearch: true,
    },
    // {
    //   title: '内容类型',
    //   dataIndex: 'contentType',
    //   valueEnum: SYS_ENUMS.NOTICE_CONTENT_TYPE,
    //   width: 130,
    //   hideInForm: true,
    //   hideInSearch: true,
    // },
    {
      title: '内容',
      dataIndex: 'contentId',
      ellipsis: true,
      hideInSearch: true,
      width: 120,//
      render: (_, record) => <div>
        {
          record.contentId ?
            <a href={`/marketing/content/edit/${record.contentId}`} target='_blank' rel="noreferrer">查看</a> : '-'
        }
      </div>
    },
    {
      title: '推送状态',
      dataIndex: 'state',
      valueEnum: SYS_ENUMS.PUSH_STATE,
      width: 130,
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '成功人数',
      dataIndex: 'successUserNum',
      ellipsis: true,
      hideInSearch: true,
      width: 100,
    },
    {
      title: '接受角色',
      dataIndex: 'userStrategy',
      ellipsis: true,
      hideInSearch: true,
      width: 200,
      render: (_, record) => <div>
        {
          record.userStrategy.map((key: any, index: number) => `${index != 0 ? '、' : ''}${SYS_ENUMS.USER_STRATEGY[key]?.text}`)
        }
      </div>
    },{
      title: '创建时间',
      dataIndex: 'gmtCreate',
      valueType: 'dateTime',
      width: 170,
      hideInSearch: true,
      hideInForm: true,
    },{
      title: '修改时间',
      dataIndex: 'gmtModified',
      valueType: 'dateTime',
      width: 170,
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      hideInSearch: true,
      hideInForm: true,
      fixed: 'right',
      render: (_, record) => [
        <a key="edit"
           onClick={() => Modal.confirm({
             title: '提示',
             icon: <ExclamationCircleOutlined/>,
             content: <span>确定要取消 <Tag color='#108ee9'>{record.contentTitle}</Tag> 吗？</span>,
             okText: '是',
             cancelText: '否',
             onOk: async () => {
               if (await pushCancel(record)) {
                 actionRef.current?.reload()
               }
             },
           })}
        >取消</a>,
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable<any, any>
        headerTitle={<Radio.Group value={auditState} onChange={(e) => {
          setAuditState(e.target.value)
          actionRef.current?.reload()
        }}>
          <Radio.Button value='ALL'>全部 {countInfo?.ALL ?? ''}</Radio.Button>
          <Radio.Button value='INIT'>初始化 {countInfo?.INIT ?? ''}</Radio.Button>
          <Radio.Button value='CANCEL'>已取消 {countInfo?.CANCEL ?? ''}</Radio.Button>
          <Radio.Button value='DOING'>执行中 {countInfo?.DOING ?? ''}</Radio.Button>
          <Radio.Button value='FINISH'>完成 {countInfo?.FINISH ?? ''}</Radio.Button>
          <Radio.Button value='FAIL'>失败 {countInfo?.FAIL ?? ''}</Radio.Button>
        </Radio.Group>}
        actionRef={actionRef}
        rowKey="key"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              auditFormRef?.resetFields()
              handleAuditVisible(true)}
            }>
            <PlusOutlined/> 新建
          </Button>
        ]}
        request={async (params) => {
          const query = {...params}
          if (auditState !== 'ALL') {
            query.state = auditState
          }
          const {data: {data, total}, code}: any = await Marketing.taskQuery(query);
          setCountInfo({...initCountInfo, [auditState]:total})
          return {data: data || [], success: isSuccess(code), total: isSuccess(code) ? total : 0};
        }}
        columns={columns}
        scroll={{ x: 1300 }}
      />

      <ModalForm
        title={`添加推送`}
        width="750px"
        form={auditFormRef}
        visible={auditVisible}
        onVisibleChange={v => {
          handleAuditVisible(v)
          if (!v) {
            auditFormRef?.resetFields()
          }
        }}
        onFinish={async (value) => {
          // @ts-ignore
          if (await pushAdd(value as any)) {
            handleAuditVisible(false);
            auditFormRef?.resetFields()
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      >
        <ProFormSelect label='推送类型' required rules={[{required: true, message: '请填选择推送类型',},]} name='pushType'
                       initialValue={SYS_ENUMS.PUSH_TYPE.NOTICE.value} options={Object.values(SYS_ENUMS.PUSH_TYPE)}/>
        <ProFormSelect label='内容' name='contentId' required rules={[{required: true, message: '请设置内容',},]}
                       request={async (params) => {
                         const {code, data} = await Marketing.contentList({
                           current: 1,
                           pageSize: 20,
                           name: params.keyWords ?? '',
                         })
                         return isSuccess(code) ? (data.data ?? []).map((item: any) => {
                           const {name, id} = item
                           return {label: `${name}`, value: id}
                         }) : []
                       }} showSearch/>
        <ProFormSelect label='目标用户' required rules={[{required: true, message: '请填选择推送类型',},]} name='userStrategy' mode="multiple"
                       initialValue={SYS_ENUMS.USER_STRATEGY.ALL} options={Object.values(SYS_ENUMS.USER_STRATEGY)}/>
      </ModalForm>
    </PageContainer>
  );
};

export default ArticleList;
